package com.wlanauth.web.core;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 此类来自Intenet,可用未做修改
 * @author zz
 * @date 2012-5-16
 * @email charles.zz.life@gmail.com
 */
public class DateTypeConverter extends
		com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter {

	private static final DateFormat[] ACCEPT_DATE_FORMATS = {
			new SimpleDateFormat("yyyy-MM-dd"),
			new SimpleDateFormat("yyyy/MM/dd"),
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
	}; // 支持转换的日期格式

	@SuppressWarnings("rawtypes")
	@Override
	public Object convertValue(Map context, Object value, Class toType) {
		// TODO Auto-generated method stub
		if (toType == Date.class) {  //浏览器向服务器提交时，进行String to Date的转换
			String dateString = null;
			
			String[] params = (String[])value;
			
			dateString = params[0];
			
			for (DateFormat format : ACCEPT_DATE_FORMATS) {
				try {
					Date d = format.parse(dateString);
					return d;
				} catch(Exception e) {
					continue;
				}
			}
			return null;
		}
		else if (toType == String.class) {   //服务器向浏览器输出时，进行Date to String的类型转换
			Date date = (Date)value;
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
		}
			return null;
		}
}
